<template>
  <el-dialog
    :model-value="modelValue"
    :title="formMode === 'create' ? '新增组织' : '编辑组织'"
    width="600px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="组织名称" prop="name">
        <el-input 
          v-model="form.name" 
          placeholder="请输入组织名称"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="组织编码" prop="code">
        <el-input 
          v-model="form.code" 
          placeholder="请输入组织编码"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
      
      <el-form-item label="地址" prop="address">
        <el-input 
          v-model="form.address" 
          type="textarea"
          placeholder="请输入地址"
          maxlength="500"
          show-word-limit
          :rows="3"
        />
      </el-form-item>
      
      <el-form-item label="联系信息" prop="contactInfo">
        <el-input 
          v-model="form.contactInfo" 
          type="textarea"
          placeholder="请输入联系信息"
          maxlength="500"
          show-word-limit
          :rows="3"
        />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input 
          v-model="form.description" 
          type="textarea"
          placeholder="请输入组织描述"
          maxlength="500"
          show-word-limit
          :rows="4"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="submitLoading"
        >
          {{ formMode === 'create' ? '创建' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { organizationAPI } from '@/api/organization'

const props = defineProps<{
  modelValue: boolean
  formMode: 'create' | 'edit'
  organizationData: any
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit'): void
  (e: 'close'): void
}>()

const formRef = ref()
const loading = ref(false)
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: undefined as number | undefined,
  name: '',
  code: '',
  status: 1,
  address: '',
  contactInfo: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入组织编码', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}

// 监听组织数据变化
watch(() => props.organizationData, (newVal) => {
  if (newVal) {
    form.id = newVal.id
    form.name = newVal.name
    form.code = newVal.code
    form.status = newVal.status
    form.address = newVal.address || ''
    form.contactInfo = newVal.contact_info || ''
    form.description = newVal.description || ''
  } else {
    // 重置表单
    form.id = undefined
    form.name = ''
    form.code = ''
    form.status = 1
    form.address = ''
    form.contactInfo = ''
    form.description = ''
  }
}, { immediate: true })

// 方法
const handleClose = () => {
  emit('update:modelValue', false)
  emit('close')
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (props.formMode === 'create') {
          await organizationAPI.createOrganization(form)
          ElMessage.success('组织创建成功')
        } else {
          if (form.id) {
            await organizationAPI.updateOrganization(form.id.toString(), form)
            ElMessage.success('组织更新成功')
          }
        }
        emit('submit')
        handleClose()
      } catch (error) {
        console.error('保存组织失败:', error)
        ElMessage.error('保存组织失败: ' + (error as Error).message)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 生命周期
onMounted(() => {
  // 组件挂载时的初始化逻辑
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>